<template>
  <div id="userRegisterPage">
    <div class="register-container">
      <div class="register-card">
        <div class="card-header">
          <h2 class="title">HanCoder</h2>
          <div class="subtitle">AI 应用生成平台</div>
          <div class="desc">创建账号，开启AI编程之旅</div>
        </div>

        <a-form
          ref="formRef"
          :model="formState"
          name="basic"
          autocomplete="off"
          @finish="handleSubmit"
          class="register-form"
        >
          <a-form-item name="userAccount" :rules="[{ required: true, message: '请输入账号' }]">
            <a-input
              v-model:value="formState.userAccount"
              placeholder="请输入账号"
              size="large"
            >
              <template #prefix>
                <UserOutlined class="input-icon" />
              </template>
            </a-input>
          </a-form-item>

          <a-form-item
            name="userPassword"
            :rules="[
              { required: true, message: '请输入密码' },
              { min: 8, message: '密码不能小于 8 位' },
            ]"
          >
            <a-input-password
              v-model:value="formState.userPassword"
              placeholder="请输入密码"
              size="large"
            >
              <template #prefix>
                <LockOutlined class="input-icon" />
              </template>
            </a-input-password>
          </a-form-item>

          <a-form-item
            name="checkPassword"
            :rules="[
              { required: true, message: '请确认密码' },
              { min: 8, message: '密码不能小于 8 位' },
              { validator: validateCheckPassword },
            ]"
          >
            <a-input-password
              v-model:value="formState.checkPassword"
              placeholder="请确认密码"
              size="large"
            >
              <template #prefix>
                <LockOutlined class="input-icon" />
              </template>
            </a-input-password>
          </a-form-item>

          <a-form-item
            name="captcha"
            :rules="[
              { required: true, message: '请输入验证码' },
              { validator: validateCaptcha },
            ]"
          >
            <CaptchaInput
              ref="captchaRef"
              v-model="formState.captcha"
              @verify="handleCaptchaVerify"
              @refresh="handleCaptchaRefresh"
            />
          </a-form-item>

          <div class="tips">
            已有账号？
            <RouterLink to="/user/login" class="login-link">立即登录</RouterLink>
          </div>

          <a-form-item>
            <a-button
              type="primary"
              html-type="submit"
              size="large"
              class="register-btn"
              :loading="loading"
            >
              注册
            </a-button>
          </a-form-item>
        </a-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router'
import { userRegister } from '@/api/userController.ts'
import { message } from 'ant-design-vue'
import { reactive, ref } from 'vue'
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue'
import CaptchaInput from '@/components/CaptchaInput.vue'
import type { FormInstance } from 'ant-design-vue'

const router = useRouter()
const formRef = ref<FormInstance>()
const captchaRef = ref<InstanceType<typeof CaptchaInput>>()
const loading = ref(false)
const currentCaptchaCode = ref('')

const formState = reactive<API.UserRegisterRequest & { captcha: string }>({
  userAccount: '',
  userPassword: '',
  checkPassword: '',
  captcha: '',
})

/**
 * 验证确认密码
 * @param rule
 * @param value
 * @param callback
 */
const validateCheckPassword = (rule: unknown, value: string, callback: (error?: Error) => void) => {
  if (value && value !== formState.userPassword) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

/**
 * 验证验证码
 * @param rule
 * @param value
 * @param callback
 */
const validateCaptcha = (rule: unknown, value: string, callback: (error?: Error) => void) => {
  if (!value) {
    callback(new Error('请输入验证码'))
  } else if (!captchaRef.value?.verifyCaptcha(value)) {
    callback(new Error('验证码错误'))
  } else {
    callback()
  }
}

/**
 * 处理验证码验证
 */
const handleCaptchaVerify = (code: string) => {
  formRef.value?.validateFields(['captcha'])
}

/**
 * 处理验证码刷新
 */
const handleCaptchaRefresh = (code: string) => {
  currentCaptchaCode.value = code
  // 清空验证码输入
  formState.captcha = ''
  formRef.value?.clearValidate(['captcha'])
}

/**
 * 提交表单
 * @param values
 */
const handleSubmit = async (values: API.UserRegisterRequest & { captcha: string }) => {
  // 验证验证码
  if (!captchaRef.value?.verifyCaptcha(values.captcha)) {
    message.error('验证码错误，请重新输入')
    captchaRef.value?.refreshCaptcha()
    return
  }

  loading.value = true
  try {
    // 提交注册请求（不包含验证码字段）
    const registerData: API.UserRegisterRequest = {
      userAccount: values.userAccount,
      userPassword: values.userPassword,
      checkPassword: values.checkPassword,
    }

    const res = await userRegister(registerData)
    // 注册成功，跳转到登录页面
    if (res.data.code === 0) {
      message.success('注册成功')
      await router.push({
        path: '/user/login',
        replace: true,
      })
    } else {
      message.error('注册失败，' + res.data.message)
      // 刷新验证码
      captchaRef.value?.refreshCaptcha()
    }
  } catch (error) {
    message.error('注册失败，请重试')
    // 刷新验证码
    captchaRef.value?.refreshCaptcha()
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
#userRegisterPage {
  background: linear-gradient(135deg, #0f172a 0%, #1e293b 25%, #334155 50%, #475569 100%);
  min-height: 100vh;
  position: relative;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 科技感背景网格 */
#userRegisterPage::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image:
    linear-gradient(rgba(0, 255, 255, 0.05) 1px, transparent 1px),
    linear-gradient(90deg, rgba(0, 255, 255, 0.05) 1px, transparent 1px),
    linear-gradient(rgba(138, 43, 226, 0.04) 1px, transparent 1px),
    linear-gradient(90deg, rgba(138, 43, 226, 0.04) 1px, transparent 1px);
  background-size:
    100px 100px,
    100px 100px,
    20px 20px,
    20px 20px;
  pointer-events: none;
  animation: gridFloat 20s ease-in-out infinite;
}

@keyframes gridFloat {
  0%, 100% { transform: translate(0, 0); }
  50% { transform: translate(2px, 2px); }
}

/* 动态光效 */
#userRegisterPage::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background:
    radial-gradient(circle at 30% 40%, rgba(0, 255, 255, 0.08) 0%, transparent 50%),
    radial-gradient(circle at 70% 60%, rgba(138, 43, 226, 0.06) 0%, transparent 50%),
    radial-gradient(circle at 50% 80%, rgba(0, 255, 127, 0.04) 0%, transparent 50%);
  pointer-events: none;
  animation: lightPulse 8s ease-in-out infinite alternate;
}

@keyframes lightPulse {
  0% { opacity: 0.5; }
  100% { opacity: 1; }
}

.register-container {
  position: relative;
  z-index: 2;
  width: 100%;
  max-width: 450px;
  padding: 20px;
}

.register-card {
  background: rgba(15, 23, 42, 0.8);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(0, 255, 255, 0.2);
  border-radius: 20px;
  padding: 40px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.4);
  position: relative;
  overflow: hidden;
}

.register-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background:
    radial-gradient(circle at 20% 20%, rgba(0, 255, 255, 0.05) 0%, transparent 50%),
    radial-gradient(circle at 80% 80%, rgba(138, 43, 226, 0.05) 0%, transparent 50%);
  pointer-events: none;
}

.card-header {
  text-align: center;
  margin-bottom: 32px;
  position: relative;
  z-index: 2;
}

.title {
  font-size: 36px;
  font-weight: 800;
  margin: 0 0 8px;
  background: linear-gradient(135deg, #00ffff 0%, #8a2be2 50%, #00ff7f 100%);
  background-size: 200% 200%;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  animation: titleShimmer 4s ease-in-out infinite;
}

@keyframes titleShimmer {
  0% { background-position: 0% 50%; }
  50% { background-position: 100% 50%; }
  100% { background-position: 200% 50%; }
}

.subtitle {
  font-size: 16px;
  color: #94a3b8;
  margin-bottom: 8px;
  font-weight: 500;
}

.desc {
  font-size: 14px;
  color: #64748b;
  opacity: 0.8;
}

.register-form {
  position: relative;
  z-index: 2;
}

.input-icon {
  color: #64748b;
}

:deep(.ant-input-affix-wrapper) {
  background: rgba(15, 23, 42, 0.8) !important;
  border: 1px solid rgba(0, 255, 255, 0.3) !important;
  border-radius: 12px;
  padding: 12px 16px;
  transition: all 0.3s ease;
}

:deep(.ant-input-affix-wrapper:focus-within) {
  border-color: rgba(0, 255, 255, 0.6) !important;
  box-shadow: 0 0 0 2px rgba(0, 255, 255, 0.2) !important;
}

:deep(.ant-input) {
  background: transparent !important;
  border: none !important;
  color: #e2e8f0 !important;
  font-size: 16px;
}

:deep(.ant-input::placeholder) {
  color: #64748b !important;
}

:deep(.ant-input-password) {
  background: transparent !important;
  color: #e2e8f0 !important;
}

.tips {
  text-align: center;
  color: #94a3b8;
  font-size: 14px;
  margin-bottom: 24px;
}

.login-link {
  color: #00ffff;
  text-decoration: none;
  font-weight: 500;
  transition: all 0.3s ease;
}

.login-link:hover {
  color: #8a2be2;
  text-shadow: 0 0 8px rgba(0, 255, 255, 0.5);
}

.register-btn {
  width: 100%;
  height: 48px;
  background: linear-gradient(135deg, #00ffff, #8a2be2) !important;
  border: none !important;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  box-shadow: 0 8px 20px rgba(0, 255, 255, 0.3);
  transition: all 0.3s ease;
}

.register-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 12px 28px rgba(0, 255, 255, 0.4) !important;
}

.register-btn:active {
  transform: translateY(0);
}

/* 响应式设计 */
@media (max-width: 480px) {
  .register-container {
    max-width: 320px;
    padding: 16px;
  }

  .register-card {
    padding: 32px 24px;
  }

  .title {
    font-size: 28px;
  }
}
</style>
